package it.antonio.ilpizze.db.index.hash.file;

import it.antonio.ilpizze.db.index.hash.Element;
import it.antonio.ilpizze.db.index.hash.ElementList;
import it.antonio.ilpizze.db.index.utils.FPerst;
import it.antonio.ilpizze.db.index.utils.FilePointer;
import it.antonio.ilpizze.db.io.IOConstants;
import it.antonio.ilpizze.db.io.IOFile;

public class FileElementList<K, V> implements ElementList<K, V>, FilePointer, IOConstants{
	/*
	 * entries
	 */
	private int degree;
	
	private IOFile file;
	
	private long position;
	private FPerst<K> keyPersister;
	private FPerst<V> valuePersister;
	
	public FileElementList(int degree, IOFile file, long position, FPerst<K> keyPersister, FPerst<V> valuePersister) {
		this.degree = degree;
		
		this.file = file;
		this.position = position;
		this.keyPersister = keyPersister;
		this.valuePersister = valuePersister;
		
	}

	@Override
	public Element<K, V> first(int index) {
		file.position(position + (index * SIZE_LONG));
		long position = file.readLong();
		if(position != -1){
			return new FileElement<K, V>(file, position, keyPersister, valuePersister);	
		} else {
			return null;
		}
	}

	@Override
	public void addFirst(int index, Element<K, V> first) {
		file.position(position + (index * SIZE_LONG));
		
		if(first == null){
			file.writeLong(-1);	
		} else {
			FileElement<K, V> fileEntry = (FileElement<K, V>) first;
			file.writeLong(fileEntry.position());	
		}
	}

	@Override
	public long position() {
		return position;
	}

	@Override
	public long space() {
		return degree * SIZE_LONG;
	}

}
